import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  SmileOutlined,
} from '@ant-design/icons';
import { Button, Layout, Menu } from 'antd';
import { useEffect, useRef, useState } from 'react';
import styles from './index.less';
import { history, useLocation, connect } from 'umi';

const { Content, Sider } = Layout;

const MenuHome = ({ current, routes, children }) => {
  const [collapsed, setCollapsed] = useState(false);
  const locations = useLocation().pathname;
  const [url, setUrl] = useState([locations]);
  const onClick = (e) => {
    // 获取key跳转
    history.push(e.key);
    setUrl([e.key]);
  };
  const toggleCollapsed = () => {
    setCollapsed(!collapsed);
  };
  /* 处理路由树 */
  const format = (arr) => {
    console.log(arr);
    let children = null;
    return (
      arr &&
      arr.map((v) => {
        if (v.menuVOS) {
          children = format(v.menuVOS);
        }
        return {
          label: v.name,
          key: v.dataUrl,
          icon: <SmileOutlined />,
          children,
        };
      })
    );
  };
  /* 过滤需要展示的子菜单 */
  const findMenu = (arr, current) => {
    let res = [];
    arr &&
      arr.filter((v) => {
        if (v.id === current) {
          res = v.menuVOS ? v.menuVOS : [];
        }
      });
    return format(res);
  };
  let [menuList, setMenuList] = useState([]);

  useEffect(() => {
    setMenuList(findMenu(routes, current));
    setUrl([locations]);
  }, [current, locations]);
  return (
    <div>
      <Layout className={styles.layouts}>
        {/* 左侧导航 */}
        <Sider collapsed={collapsed}>
          <div>
            <Menu
              onClick={onClick}
              defaultSelectedKeys={url}
              mode="inline"
              theme="light"
              items={menuList}
              multiple={false}
              className={styles.menu}
            />
            <Button
              type="dashed"
              onClick={toggleCollapsed}
              className={styles.btn_control}
            >
              {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            </Button>
          </div>
        </Sider>
        <Content className={styles.mContent}>{children}</Content>
      </Layout>
    </div>
  );
};
/* dva */
const mapStateToProps = (state) => {
  return {
    routes: state.global.routes,
  };
};
export default connect(mapStateToProps)(MenuHome);
